package com.heima.user.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult<Map<String, Object>> login(LoginDto loginDto) {
        // 判断是否是游客登录
        if (StrUtil.hasEmpty(loginDto.getPassword(), loginDto.getPhone())) {
            return ResponseResult.okResult(MapUtil.<String, Object>builder()
                    .put("token", AppJwtUtil.getToken(0L))
                    .build());
        }
        // 根据手机号查询用户是否存在
        ApUser apUser = this.lambdaQuery().eq(loginDto.getPhone() != null, ApUser::getPhone, loginDto.getPhone()).one();

        if (ObjectUtil.isEmpty(apUser)) {
            // 用户不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "此手机号对应的用户不存在");
        }

        // 校验密码是否正确
        String md5Hex = DigestUtil.md5Hex(loginDto.getPassword() + apUser.getSalt());

        if (ObjectUtil.notEqual(md5Hex, apUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        // 用户验证成功， 生成token
        String token = AppJwtUtil.getToken(Convert.toLong(apUser.getId()));
        apUser.setPassword(null);
        apUser.setSalt(null);

        return ResponseResult.okResult(MapUtil.<String, Object>builder()
                .put("token", token)
                .put("user", apUser)
                .build());
    }
}
